const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
require('dotenv').config();
const { autoInitDatabase } = require('./config/database');
const autoSeedData = require('./scripts/auto-seed');

// 导入数据库配置和模型
const { sequelize, testConnection } = require('./config/database');
require('./models'); // 确保所有模型都被加载

const app = express();
const PORT = process.env.PORT || 3002;

// 中间件
app.use(helmet()); // 安全头
app.use(cors()); // 跨域支持
app.use(morgan('combined')); // 日志
app.use(express.json()); // JSON解析
app.use(express.urlencoded({ extended: true })); // URL编码解析

// 路由
const weatherRoutes = require('./routes/weather');
const geocodeRoutes = require('./routes/geocode');
const poiRoutes = require('./routes/poi');
const routeRoutes = require('./routes/route');
const newsRoutes = require('./routes/news');
const userRoutes = require('./routes/user');

app.use('/api/weather', weatherRoutes);
app.use('/api/geocode', geocodeRoutes);
app.use('/api/poi', poiRoutes);
app.use('/api/route', routeRoutes);
app.use('/api/news', newsRoutes);
app.use('/api/user', userRoutes);

// 根路径
app.get('/', (req, res) => {
  res.json({
    message: 'Nuxt3 Backend API Server',
    version: '1.0.0',
    endpoints: {
      health: '/health',
      dbStatus: '/db-status',
      weather: '/api/weather',
      geocode: '/api/geocode',
      poi: '/api/poi',
      route: '/api/route',
      news: '/api/news'
    },
    timestamp: new Date().toISOString()
  });
});

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    environment: process.env.NODE_ENV || 'development'
  });
});

// 数据库状态检查
app.get('/db-status', async (req, res) => {
  try {
    const isConnected = await testConnection();
    res.json({
      database: isConnected ? 'connected' : 'disconnected',
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({
      database: 'error',
      error: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    error: 'Not Found',
    message: `Route ${req.originalUrl} not found`,
    timestamp: new Date().toISOString()
  });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('Server Error:', error);
  res.status(500).json({
    error: 'Internal Server Error',
    message: error.message,
    timestamp: new Date().toISOString()
  });
});

// 启动服务器
const startServer = async () => {
  try {
    console.log('🚀 启动后端服务器...');
    console.log('📍 服务器地址: http://localhost:' + PORT);
    
    // 自动初始化数据库
    console.log('🔌 初始化数据库连接...');
    const dbInitResult = await autoInitDatabase();
    
    if (dbInitResult) {
      // 自动填充数据
      console.log('🌱 检查并填充数据...');
      await autoSeedData();
    } else {
      console.warn('⚠️  数据库初始化失败，服务器将继续启动但API可能无法正常工作');
    }
    
    // 启动HTTP服务器
    app.listen(PORT, () => {
      console.log('✅ 后端服务器启动成功!');
      console.log(`🌐 服务器地址: http://localhost:${PORT}`);
      console.log(`📊 健康检查: http://localhost:${PORT}/health`);
      console.log(`🗄️  数据库状态: http://localhost:${PORT}/db-status`);
      console.log('📝 API文档:');
      console.log(`   - 天气API: http://localhost:${PORT}/api/weather`);
      console.log(`   - 地理编码API: http://localhost:${PORT}/api/geocode`);
      console.log(`   - POI搜索API: http://localhost:${PORT}/api/poi`);
      console.log(`   - 路线规划API: http://localhost:${PORT}/api/route`);
      console.log(`   - 新闻API: http://localhost:${PORT}/api/news`);
      console.log('');
      console.log('按 Ctrl+C 停止服务器');
    });
    
  } catch (error) {
    console.error('❌ 服务器启动失败:', error.message);
    process.exit(1);
  }
};

// 优雅关闭
process.on('SIGINT', () => {
  console.log('\n🛑 正在关闭服务器...');
  process.exit(0);
});

process.on('SIGTERM', () => {
  console.log('\n🛑 正在关闭服务器...');
  process.exit(0);
});

// 启动服务器
startServer();

module.exports = app; 